package school30;

import java.util.Hashtable;
import school30.ui.events.KeyEvent;

public class KeyboardHandler {

    private TextHandler textHandler;
    private Hashtable keyPressLetters = new Hashtable();
    private Hashtable keyHold = new Hashtable();
    int cur_key_n;
    int last_pressed_key = -1;
    long lastPressTime;

    public TextHandler getTextHandler() {
        return textHandler;
    }

    public void setTextHandler(TextHandler textHandler) {
        this.textHandler = textHandler;
    }
    
    public void initDefault() {
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM1),
                (Object) (new char[]{',', '.', '-'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM2),
                (Object) (new char[]{'a', 'b', 'c'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM3),
                (Object) (new char[]{'d', 'e', 'f'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM4),
                (Object) (new char[]{'g', 'h', 'i'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM5),
                (Object) (new char[]{'j', 'k', 'l'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM6),
                (Object) (new char[]{'m', 'n', 'o'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM7),
                (Object) (new char[]{'p', 'q', 'r', 's'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM8),
                (Object) (new char[]{'t', 'u', 'v'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM9),
                (Object) (new char[]{'w', 'x', 'y', 'z'}));
        keyPressLetters.put(new Integer(KeyEvent.KEY_NUM0),
                (Object) (new char[]{' '}));
    }

    public void start() {
    }

    public void keyPressed(int code) {
    }

    public void runTextHandler(char c)
    {
        if (textHandler != null)
          textHandler.handleCharEnter(c);
    }
    
    public void keyReleased(int code) {
        if (last_pressed_key == code && System.currentTimeMillis() - lastPressTime < 500) {
            char[] arr = (char[]) keyPressLetters.get(new Integer(code));
            if (arr != null) {
                cur_key_n = (cur_key_n + 1) % arr.length;
                System.out.println("KeyPress!");
            }
        } else if (last_pressed_key != -1) {
            char[] arr = (char[]) keyPressLetters.get(new Integer(last_pressed_key));
            if (arr != null) {
                runTextHandler(arr[cur_key_n]);
                cur_key_n = 0;
            }
        } else {
            cur_key_n = 0;
        }
        lastPressTime = System.currentTimeMillis();
        last_pressed_key = code;
    }
}
